package com.wzdigit.wms.raw.service.mid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.wms.basic.client.response.basic.SkuBaseResponse;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnHeaderMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.raw.constant.SyncTypeConstant;
import com.wzdigit.wms.raw.domain.dto.HouseQaStatus;
import com.wzdigit.wms.raw.domain.dto.IfWearepartHeaderDto;
import com.wzdigit.wms.raw.domain.mid.IfWearepartDtl;
import com.wzdigit.wms.raw.domain.mid.IfWearepartHeader;
import com.wzdigit.wms.raw.exception.SyncException;
import com.wzdigit.wms.raw.mapper.mid.IfWearepartDtlMapper;
import com.wzdigit.wms.raw.mapper.mid.IfWearepartHeaderMapper;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-采购订单 同步 采购订单
 * </p>
 *
 * @author chao shuai
 * @since 2021-06-10
 */
@Service
public class IfWearepartHeaderService {

    @Autowired
    private IfWearepartHeaderMapper ifWearepartHeaderMapper;

    @Autowired
    private IfWearepartDtlMapper ifWearepartDtlMapper;

    @Autowired
    private GdnHeaderMapper gdnHeaderMapper;

    @Autowired
    private GdnDtlMapper gdnDtlMapper;

    @Autowired
    private AsnHeaderMapper asnHeaderMapper;

    @Autowired
    private AsnDtlMapper asnDtlMapper;

    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi  basicVendorApi;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Autowired
    CodeMappingService codeMappingService;


    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;


    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;

    @Autowired
    private  MappingHouseService mappingHouseService;



    private final String syncType = SyncTypeConstant.IF_WEAREPART_TO_GDN_OR_ASN;

    public List<IfWearepartHeaderDto> selectSyncData() {
        ArrayList<IfWearepartHeaderDto> ifWearepartHeaderDtos = new ArrayList<>();
        QueryWrapper<IfWearepartHeader> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("Attribute10","1").or().isNull("Attribute10");
        List<IfWearepartHeader> selectSyncData = ifWearepartHeaderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfWearepartHeader ifWearepartHeader : selectSyncData) {
                IfWearepartHeaderDto ifWearepartHeaderDto = new IfWearepartHeaderDto();
                BeanUtil.copyNonNull(ifWearepartHeader, ifWearepartHeaderDto);
                List<IfWearepartDtl> ifSalesreturnDtls = ifWearepartDtlMapper.selectList(new QueryWrapper<>(
                        new IfWearepartDtl().setIfWearepartHeaderId(ifWearepartHeader.getIfWearepartHeaderId())
                ));
                ifWearepartHeaderDto.setIfWearepartHeaderDtoList(ifSalesreturnDtls);
                ifWearepartHeaderDtos.add(ifWearepartHeaderDto);
            }

        }
        return ifWearepartHeaderDtos;
    }




    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataGdn(IfWearepartHeaderDto data, boolean isSyncError) throws Exception {
        String zpckno = data.getZpckno(); //委外单号--》发货单号or收货通知单号
        //查询供应商信息

        List<IfWearepartDtl> ifWearepartDtlList = data.getIfWearepartHeaderDtoList();

        GdnHeader gdnHeader = new GdnHeader();
        //同步主表信息
        gdnHeader.setGdnNo(zpckno);
        gdnHeader.setGdnType(GdnTypeEnum.D21.code);//易损件领料
        gdnHeader.setFactory(data.getWerks());
        gdnHeader.setMfgPlant(data.getZwerks());
        gdnHeader.setSourceType(data.getZtype());
        gdnHeader.setGdnCreateUser(data.getCreateUser());
        gdnHeader.setGdnCreateTime(data.getCreateTime());

        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);
        gdnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));

        GdnHeader gdnHeaderRecord = gdnHeaderMapper.selectOne(new QueryWrapper<>(new GdnHeader().setGdnNo(zpckno)));
        if (gdnHeaderRecord == null) {
            gdnHeader.setStatus( GdnHeaderStatusEnum.CREATE.getCode());//新建状态
            gdnHeader.setCreateTime(new Date());
            gdnHeader.setCreateUser("system");
            gdnHeaderMapper.insert(gdnHeader);
        } else {
            gdnHeader.setModifyTime(new Date());
            gdnHeader.setModifyUser("system");
            gdnHeader.setGdnHeaderId(gdnHeaderRecord.getGdnHeaderId());
            gdnHeaderMapper.updateById(gdnHeader);
        }
        //同步明细，生成行号
        //获取最大行号
        Integer maxLineNo = gdnDtlMapper.selectMaxLineId(gdnHeader.getGdnHeaderId());
        if(maxLineNo == null){
            maxLineNo = 1 ;
        }

        for (IfWearepartDtl ifWearepartDtl : ifWearepartDtlList) {
            //查询SKUID
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifWearepartDtl.getMatnr());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, zpckno, "物料编码" + ifWearepartDtl.getMatnr() + "不存在");
            }
            //处理仓库信息
            HouseQaStatus houseQaStatus = mappingHouseService.getWmsHourseIdBySapHourseCode(ifWearepartDtl.getLgortOut());
            if(houseQaStatus==null){
                throw new SyncException(syncType, zpckno, "SAP仓库编码" + ifWearepartDtl.getLgortOut() + "无法转换成WMS仓库");
            }
            GdnDtl gdnDtl = new GdnDtl();
            gdnDtl.setGdnHeaderId(gdnHeader.getGdnHeaderId());
            gdnDtl.setSkuId(sku.getSkuId());
            gdnDtl.setOrderQty(ifWearepartDtl.getMenge());
            gdnDtl.setUnit(ifWearepartDtl.getMeins());
            gdnDtl.setWhsId(houseQaStatus.getWhsId());
            gdnDtl.setSourceShipNotice(ifWearepartDtl.getVbeln());//来源通知单号
            gdnDtl.setSourceShipNoticeItem(ifWearepartDtl.getPosnr());//来源通知单行号
            gdnDtl.setPoNo(ifWearepartDtl.getZvbeln());
            gdnDtl.setGdnRef1(ifWearepartDtl.getDispo());
            gdnDtl.setGdnRef2(ifWearepartDtl.getDsnam());
            gdnDtl.setGdnRef5(ifWearepartDtl.getItemguid());//行号存储在自定义字段
            gdnDtl.setComments(ifWearepartDtl.getRemark());
            gdnDtl.setStatus(Integer.parseInt(ifWearepartDtl.getZstatus()));//状态
            gdnDtl.setDemandTime(ifWearepartDtl.getEdatu());


            GdnDtl gdnDtlRecord = gdnDtlMapper.selectOne(new QueryWrapper<>(new GdnDtl().setGdnHeaderId(gdnHeader.getGdnHeaderId()).setGdnRef5(ifWearepartDtl.getItemguid())));
            if (gdnDtlRecord == null) {
                gdnDtl.setCreateUser("system");
                gdnDtl.setCreateTime(new Date());
                gdnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());//新建状态
                gdnDtl.setQaStatus(QaStatusEnum.OK.code);//品质状态
                gdnDtl.setGdnLineNo(maxLineNo++);//新增行号加1
                try {
                    gdnDtlMapper.insert(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, zpckno, e.getMessage());
                }
            } else {
                gdnDtl.setModifyUser("system");
                gdnDtl.setModifyTime(new Date());
                gdnDtl.setGdnDtlId(gdnDtlRecord.getGdnDtlId());
                gdnDtl.setGdnLineNo(gdnDtlRecord.getGdnLineNo());
                try {
                    gdnDtlMapper.updateById(gdnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, zpckno, e.getMessage());
                }
            }
            int row = ifWearepartHeaderMapper.updateFlagById(data.getIfWearepartHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, zpckno);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, zpckno);
            }
        }

    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncDataAsn(IfWearepartHeaderDto data, boolean isSyncError) throws Exception {
        String zpckno = data.getZpckno();
        //查询供应商信息
        List<IfWearepartDtl> ifWearepartDtlList = data.getIfWearepartHeaderDtoList();
        AsnHeader asnHeader = new AsnHeader();
        //同步主表信息
        asnHeader.setAsnNo(zpckno);
        asnHeader.setAsnType(AsnTypeEnum.R16.code);
        asnHeader.setMfgPlant(data.getZwerks());
        asnHeader.setFactory(data.getWerks());
        asnHeader.setSourceType(data.getZtype());
        asnHeader.setAsnCreateUser(data.getCreateUser());
        asnHeader.setAsnCreateTime(data.getCreateTime());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);
        asnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));


        AsnHeader asnHeaderRecord = asnHeaderMapper.selectOne(new QueryWrapper<>(new AsnHeader().setAsnNo(zpckno)));
        if (asnHeaderRecord == null) {
            asnHeader.setCreateUser("system");
            asnHeader.setCreateTime(new Date());
            asnHeader.setStatus(AsnHeaderStatusEnum.CREATE.code);  //到货通知单状态
            asnHeader.setReleaseStatus(AsnHeaderStatusEnum.CANCEL.code); //ASN释放状态
            asnHeader.setQcStatus( QaStatusEnum.OK.code); //质检状态
            asnHeader.setPriority(0); //优先级
            asnHeaderMapper.insert(asnHeader);
        } else {
            asnHeader.setModifyTime(new Date());
            asnHeader.setModifyUser("system");
            asnHeader.setAsnHeaderId(asnHeaderRecord.getAsnHeaderId());
            asnHeaderMapper.updateById(asnHeader);
        }

        //同步明细
        for (IfWearepartDtl ifWearepartDtl : ifWearepartDtlList) {
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifWearepartDtl.getMatnr());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, zpckno, "物料编码" + ifWearepartDtl.getMatnr() + "不存在");
            }
            //处理仓库信息
            HouseQaStatus houseQaStatus = mappingHouseService.getWmsHourseIdBySapHourseCode(ifWearepartDtl.getLgortIn());
            if(houseQaStatus==null){
                throw new SyncException(syncType, zpckno, "SAP仓库编码" + ifWearepartDtl.getLgortIn() + "无法转换成WMS仓库");
            }
            AsnDtl asnDtl = new AsnDtl();
            asnDtl.setAsnHeaderId(asnHeader.getAsnHeaderId());
            asnDtl.setAsnNo(asnHeader.getAsnNo());
            asnDtl.setAsnLineNo(ifWearepartDtl.getItemguid());
            asnDtl.setSkuId(sku.getSkuId());
            asnDtl.setSkuDesc(sku.getDescCn());
            asnDtl.setOrderQty(ifWearepartDtl.getMenge());
            asnDtl.setOrderQtyEa(ifWearepartDtl.getMenge());
            asnDtl.setUnit(ifWearepartDtl.getMeins());
            asnDtl.setSourceNo(ifWearepartDtl.getVbeln());
            asnDtl.setSourceLineNo(ifWearepartDtl.getPosnr());
            asnDtl.setPoNo(ifWearepartDtl.getZvbeln());
            asnDtl.setAsnRef1(ifWearepartDtl.getDispo());
            asnDtl.setAsnRef2(ifWearepartDtl.getDsnam());
            asnDtl.setWhsId(houseQaStatus.getWhsId());
            asnDtl.setComments(ifWearepartDtl.getRemark());
            asnDtl.setStatus(Integer.parseInt(ifWearepartDtl.getZstatus()));
            asnDtl.setCreateTime(ifWearepartDtl.getCreateTime());
            asnDtl.setCreateUser(ifWearepartDtl.getCreateUser());
            //TODO 来源单号存储

            //处理行号
            /*Integer maxLineNo = asnDtlMapper.selectMaxLineId(asnHeader.getAsnHeaderId());
            if(maxLineNo==null){
                maxLineNo = 1;
            }*/

            AsnDtl asnDtlRecord = asnDtlMapper.selectOne(new QueryWrapper<>(new AsnDtl().setAsnHeaderId(asnHeader.getAsnHeaderId()).setAsnLineNo(ifWearepartDtl.getItemguid())));
            if (asnDtlRecord == null) {
                asnDtl.setCreateUser("system");
                asnDtl.setCreateTime(new Date());
                asnDtl.setQaStatus(QaStatusEnum.OK.code);
                asnDtl.setQcStatus(QcStatusEnum.已创建质检单.getCode());
               //  asnDtl.setAsnLineNo(maxLineNo+"");
               // maxLineNo++;
                try {
                    asnDtlMapper.insert(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, zpckno, e.getMessage());
                }
            } else {
                asnDtl.setModifyUser("system");
                asnDtl.setModifyTime(new Date());
                asnDtl.setAsnDtlId(asnDtlRecord.getAsnDtlId());
                asnDtl.setAsnLineNo(asnDtlRecord.getAsnLineNo());
                try {
                    asnDtlMapper.updateById(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, zpckno, e.getMessage());
                }
            }
            ifWearepartHeaderMapper.updateFlagById(data.getIfWearepartHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, zpckno);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, zpckno);
            }
        }

    }

}
